﻿using System.Net.Http.Headers;
using Blazored.LocalStorage;
using BPM.Web.Shared.Constants;
using BPM.Web.Shared.Extensions;

namespace BPM.Web.Shared.Auth
{
    public class AuthenticationHeaderHandler : DelegatingHandler
    {

        private readonly ILocalStorageService _storage;
        public AuthenticationHeaderHandler(ILocalStorageService storage)
        {
            _storage = storage;
        }

        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request.Headers.Authorization?.Scheme != "Bearer")
            {
                var accessToken = await _storage.GetItemAsync<string>(StorageConstants.AccessToken);
                var refreshToken = await _storage.GetItemAsync<string>(StorageConstants.RefreshToken);
                if (!string.IsNullOrWhiteSpace(accessToken))
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    if (!string.IsNullOrWhiteSpace(refreshToken))
                    {
                        //判断token过期状态
                        var exp = accessToken.GetClaims().FirstOrDefault(x => x.Type.Equals("exp"))?.Value;
                        var expTime = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(exp));
                        var timeUTC = DateTime.UtcNow;
                        var diff = expTime - timeUTC;
                        if (diff.TotalMinutes <= 1)
                        {
                            request.Headers.TryAddWithoutValidation("X-Authorization", $"Bearer {refreshToken}");
                        }
                    }
                }
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}
